import React, { useState, useEffect } from 'react';
import { trace, info, error, debug, warn, attachConsole } from '@tauri-apps/plugin-log';
import { 
  Box, 
  Typography, 
  Button, 
  Paper, 
  Divider, 
  TextField, 
  Select, 
  MenuItem, 
  FormControl, 
  InputLabel, 
  Grid, 
  Tooltip, 
  IconButton,
  Stack
} from '@mui/material';
import { ContentCopy as CopyIcon, ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { appLogDir } from '@tauri-apps/api/path';

function LogCasePage() {
  const navigate = useNavigate();
  const [message, setMessage] = useState('这是一条日志消息');
  const [logLevel, setLogLevel] = useState('info');
  const [consoleAttached, setConsoleAttached] = useState(false);
  const [detachFunction, setDetachFunction] = useState(null);
  const [output, setOutput] = useState([]);
  const [logDirPath, setLogDirPath] = useState('加载中...');
  const [copyTooltip, setCopyTooltip] = useState('复制路径');

  // 添加日志到输出区域
  const addOutput = (level, msg) => {
    const timestamp = new Date().toISOString();
    setOutput(prev => [...prev, { level, msg, timestamp }]);
  };

  // 发送日志
  const sendLog = () => {
    switch (logLevel) {
      case 'trace':
        trace(message);
        addOutput('TRACE', message);
        break;
      case 'debug':
        debug(message);
        addOutput('DEBUG', message);
        break;
      case 'info':
        info(message);
        addOutput('INFO', message);
        break;
      case 'warn':
        warn(message);
        addOutput('WARN', message);
        break;
      case 'error':
        error(message);
        addOutput('ERROR', message);
        break;
    }
  };

  // 连接到控制台
  const connectConsole = async () => {
    try {
      const detach = await attachConsole();
      setDetachFunction(() => detach);
      setConsoleAttached(true);
      addOutput('SYSTEM', '已连接到浏览器控制台');
    } catch (e) {
      addOutput('ERROR', `连接控制台失败: ${e.toString()}`);
    }
  };

  // 断开控制台连接
  const disconnectConsole = () => {
    if (detachFunction) {
      detachFunction();
      setDetachFunction(null);
      setConsoleAttached(false);
      addOutput('SYSTEM', '已断开浏览器控制台连接');
    }
  };

  // 清空输出
  const clearOutput = () => {
    setOutput([]);
  };
  
  // 复制日志目录路径
  const copyLogDir = () => {
    if (logDirPath !== '加载中...') {
      navigator.clipboard.writeText(logDirPath)
        .then(() => {
          setCopyTooltip('已复制!');
          setTimeout(() => setCopyTooltip('复制路径'), 2000);
        })
        .catch(err => {
          console.error('复制失败:', err);
          addOutput('ERROR', `复制路径失败: ${err.toString()}`);
        });
    }
  };

  // 重新获取日志目录
  const retryGetLogDir = async () => {
    setLogDirPath('加载中...');
    addOutput('SYSTEM', '正在重新获取日志目录...');
    
    try {
      const dir = await appLogDir();
      setLogDirPath(dir);
      console.log("日志目录：", dir);
      addOutput('SYSTEM', `成功获取日志目录: ${dir}`);
    } catch (err) {
      console.error("获取日志目录失败:", err);
      setLogDirPath('获取失败');
      addOutput('ERROR', `获取日志目录失败: ${err.toString()}`);
      
      // 这里不需要重复添加备用建议，因为会在日志中造成太多重复
    }
  };

  // 组件加载时获取日志目录
  useEffect(() => {
    const fetchLogDir = async () => {
      try {
        const dir = await appLogDir();
        setLogDirPath(dir);
        console.log("日志目录：", dir);
        addOutput('SYSTEM', `成功获取日志目录: ${dir}`);
      } catch (err) {
        console.error("获取日志目录失败:", err);
        setLogDirPath('获取失败');
        addOutput('ERROR', `获取日志目录失败: ${err.toString()}`);
        
        // 尝试使用备用方法获取
        try {
          // 检查操作系统类型来决定使用哪种路径格式
          const platform = window.navigator.platform.toLowerCase();
          let suggestedPath = '';
          
          if (platform.includes('win')) {
            suggestedPath = 'C:\\Users\\[用户名]\\AppData\\Roaming\\[应用名]\\logs\\';
          } else if (platform.includes('mac')) {
            suggestedPath = '~/Library/Logs/[应用名]/';
          } else {
            suggestedPath = '~/.local/share/[应用名]/logs/';
          }
          
          addOutput('INFO', `建议手动查看此路径: ${suggestedPath}`);
        } catch (backupErr) {
          console.error("备用提示也失败了:", backupErr);
        }
      }
    };
    
    fetchLogDir();
    
    return () => {
      if (detachFunction) {
        detachFunction();
      }
    };
  }, [detachFunction]);

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" alignItems="center" spacing={2} sx={{ mb: 3 }}>
        <IconButton 
          onClick={() => navigate('/')}
          sx={{ color: 'text.primary' }}
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h4" component="h1">
          日志记录
        </Typography>
      </Stack>

      <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
        <Typography variant="h6" gutterBottom>
          使用 Tauri 日志插件
        </Typography>
        <Typography variant="body2" color="text.secondary" paragraph>
          此示例展示了如何使用 @tauri-apps/plugin-log 在应用程序中记录日志，并将日志输出到多个目标。
        </Typography>

        <Box sx={{ mb: 3 }}>
          <Grid container spacing={2} alignItems="center">
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="日志消息"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                variant="outlined"
                size="small"
              />
            </Grid>
            <Grid item xs={12} sm={3}>
              <FormControl fullWidth size="small">
                <InputLabel>日志级别</InputLabel>
                <Select
                  value={logLevel}
                  label="日志级别"
                  onChange={(e) => setLogLevel(e.target.value)}
                >
                  <MenuItem value="trace">Trace</MenuItem>
                  <MenuItem value="debug">Debug</MenuItem>
                  <MenuItem value="info">Info</MenuItem>
                  <MenuItem value="warn">Warn</MenuItem>
                  <MenuItem value="error">Error</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} sm={3}>
              <Button
                fullWidth
                variant="contained"
                color="primary"
                onClick={sendLog}
              >
                发送日志
              </Button>
            </Grid>
          </Grid>
        </Box>

        <Box sx={{ mb: 2 }}>
          <Grid container spacing={2}>
            <Grid item>
              <Button
                variant="outlined"
                color="primary"
                onClick={connectConsole}
                disabled={consoleAttached}
              >
                连接控制台
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                color="secondary"
                onClick={disconnectConsole}
                disabled={!consoleAttached}
              >
                断开控制台
              </Button>
            </Grid>
            <Grid item>
              <Button
                variant="outlined"
                onClick={clearOutput}
              >
                清空输出
              </Button>
            </Grid>
          </Grid>
        </Box>

        <Divider sx={{ my: 2 }} />

        <Typography variant="h6" gutterBottom>
          日志输出
        </Typography>
        <Box
          sx={{
            maxHeight: 300,
            overflow: 'auto',
            backgroundColor: '#f5f5f5',
            p: 2,
            borderRadius: 1,
            fontFamily: 'monospace',
            fontSize: '0.875rem'
          }}
        >
          {output.length > 0 ? (
            output.map((log, index) => (
              <Typography key={index} sx={{ 
                mb: 0.5, 
                color: log.level === 'ERROR' ? 'error.main' : 
                       log.level === 'WARN' ? 'warning.main' : 
                       log.level === 'INFO' ? 'info.main' : 
                       log.level === 'DEBUG' ? 'success.main' : 
                       log.level === 'SYSTEM' ? 'secondary.main' : 'text.primary'
              }}>
                [{log.timestamp.split('T')[1].split('.')[0]}] [{log.level}] {log.msg}
              </Typography>
            ))
          ) : (
            <Typography color="text.secondary">
              暂无日志输出，请发送一条日志...
            </Typography>
          )}
        </Box>
      </Paper>

      <Paper elevation={3} sx={{ p: 3 }}>
        <Typography variant="h6" gutterBottom>
          日志文件位置
        </Typography>
        <Typography variant="body2" paragraph>
          日志插件会自动将日志写入到以下目录：
        </Typography>
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
          <TextField
            fullWidth
            variant="outlined"
            size="small"
            value={logDirPath}
            InputProps={{
              readOnly: true,
            }}
          />
          <Tooltip title={copyTooltip}>
            <IconButton onClick={copyLogDir} sx={{ ml: 1 }}>
              <CopyIcon />
            </IconButton>
          </Tooltip>
        </Box>
        <Button variant="outlined" onClick={retryGetLogDir}>
          重新获取路径
        </Button>
        <Box sx={{ mt: 2 }}>
          <Typography variant="body2" color="text.secondary">
            日志文件通常保存在系统的标准日志位置，您可以在上面显示的路径中找到应用程序的日志文件。
          </Typography>
        </Box>
      </Paper>
    </Box>
  );
}

export default LogCasePage; 